
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>{{ config.title || '个人网站' }}</title>
    <!-- 引入Vue.js -->
    <script src="https://cdn.jsdelivr.net/npm/vue@3.2.0/dist/vue.global.prod.js"></script>
    <!-- 在Vue.js后引入marked -->
    <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
    <link id="theme-css" rel="stylesheet" href="style/default.css">
</head>
<body>
<div id="app">
    <!-- 语言切换按钮 -->
    <div class="lang-switcher">
        <button @click="switchLang('zh')">中文</button>
        <button @click="switchLang('en')">English</button>
    </div>

    <!-- 头部 -->
    <header>
        <h1>{{ config.title || '默认标题' }}</h1>
        <p>{{ config.subtitle || '默认副标题' }}</p>
    </header>

    <!-- 导航 -->
    <nav v-if="currentView === 'list'">
        <ul>
            <li v-for="category in categories"
                :key="category"
                :class="{ active: (lang === 'zh' ? activeCategoryZh : activeCategoryEn) === category }"
                @click="filterByCategory(category)">
                {{ category }}
            </li>
            <!-- 新增：关于页菜单 -->
            <li @click="goToAboutPage">
                <div v-if="lang.value === 'zh'">关于</div>
                <div v-else>About</div>
            </li>
        </ul>
    </nav>

    <!-- 返回按钮 -->
    <button v-if="currentView === 'article'" @click="goBackToList" class="back-button">
        <div v-if="lang === 'zh'">← 返回文章列表</div>
        <div v-else>← Back to article list</div>
    </button>

    <!-- 文章列表 -->
    <section v-if="currentView === 'list'" id="article-list">
        <div v-for="article in paginatedArticles" class="article-card">
            <div class="article-content">
                <h2>
                    <a href="#" @click.prevent="loadAndRenderArticle(article.path)">
                        {{ article.title }}
                    </a>
                </h2>
                <div class="article-meta">
                    <span>{{ article.category }}</span>
                    <span>{{ formatDate(article.lastModified) }}</span>
                </div>
                <p class="article-excerpt">{{ article.excerpt || '点击阅读全文...' }}</p>
                <a href="#" @click.prevent="loadAndRenderArticle(article.path)" class="read-more">阅读全文</a>
            </div>
        </div>
    </section>

    <!-- 分页导航 -->
    <div v-if="currentView === 'list' && totalPages > 1" class="pagination">
        <button @click="setPage(currentPage - 1)" :disabled="currentPage === 1">上一页</button>
        <span v-for="page in totalPages" :key="page">
            <button @click="setPage(page)" :class="{ active: page === currentPage }">
                {{ page }}
            </button>
        </span>
        <button @click="setPage(currentPage + 1)" :disabled="currentPage === totalPages">下一页</button>
    </div>

    <!-- 文章详情 -->
    <section v-if="currentView === 'article'" class="article-detail">
        <div class="article-header">
            <h1>{{ currentArticle.title }}</h1>
            <div class="article-meta-large">
                <span>分类：{{ currentArticle.category }}</span>
                <span>更新：{{ formatDate(currentArticle.lastModified) }}</span>
                <span>作者：{{ config.author || '老韩' }}</span>
            </div>
        </div>
        <div class="markdown-body" v-html="articleContent"></div>
    </section>

    <!-- 关于页 -->
    <section v-if="currentView === 'about'" class="about-page">
        <h2 v-if="lang.value === 'zh'">关于</h2>
        <h2 v-else>About</h2>
        <div class="markdown-body" v-html="aboutContent"></div>
        <button @click="goBackToList">
            <div v-if="lang.value === 'zh'">← 返回首页</div>
            <div v-else>← Back to Home</div>
        </button>
    </section>

    <!-- 主题切换 -->
    <div class="theme-switcher">
        <button @click="changeTheme('default')">默认蓝</button>
        <button @click="changeTheme('theme-dark')">深空黑</button>
    </div>

    <!-- 页脚 -->
    <footer>
        <p>{{ config.copyright || '© 默认版权' }} |
            <span v-if="config.beian">{{ config.beian }}</span>
        </p>
    </footer>
</div>

<script type="module">    import { ref, onMounted, computed, createApp } from 'https://unpkg.com/vue@3.2.0/dist/vue.esm-browser.prod.js';

window.marked.setOptions({
    langPrefix: 'language-'
});

const articles = ref([]);
const categories = ref([]);
const activeCategoryZh = ref('首页');
const activeCategoryEn = ref('Home');
const currentView = ref('list');
const articleContent = ref('');
const currentArticle = ref({});
const aboutContent = ref('');
const currentPage = ref(1);
const itemsPerPage = 5;
const config = ref({
    title: '个人网站',
    subtitle: '默认副标题',
    author: '老韩',
    copyright: '© 默认版权',
    beian: ''
});
const lang = ref(localStorage.getItem('lang') || 'zh');

// 过滤文章
const filteredArticles = computed(() => {
    const currentLang = lang.value;
    if (currentLang === 'zh') {
        return activeCategoryZh.value === '首页' ?
            articles.value :
            articles.value.filter(a => a.category === activeCategoryZh.value);
    } else {
        return activeCategoryEn.value === 'Home' ?
            articles.value :
            articles.value.filter(a => a.category === activeCategoryEn.value);
    }
});

// 分页计算属性
const totalPages = computed(() => Math.ceil(filteredArticles.value.length / itemsPerPage));

const paginatedArticles = computed(() => {
    const start = (currentPage.value - 1) * itemsPerPage;
    return filteredArticles.value.slice(start, start + itemsPerPage);
});

function setPage(page) {
    if (page >= 1 && page <= totalPages.value) currentPage.value = page;
}

function formatDate(date) {
    return new Date(date).toLocaleDateString();
}

function changeTheme(themeName) {
    const themeLink = document.getElementById('theme-css');
    if (themeLink) {
        themeLink.href = `style/${themeName}.css`;
        localStorage.setItem('selectedTheme', themeName);
    }
}

function goBackToList() {
    currentView.value = 'list';
    window.location.hash = '';
}

async function handleHashChange() {
    if (window.location.hash.startsWith('#article/')) {
        const path = decodeURIComponent(window.location.hash.slice(9));
        try {
            const response = await fetch(path);
            if (!response.ok) throw new Error('加载失败');
            const markdown = await response.text();
            articleContent.value = marked.parse(markdown);
            console.log('articleContent:', articleContent.value);
            currentView.value = 'article';
            const found = articles.value.find(a => a.path === path);
            if (found) currentArticle.value = found;
        } catch (e) {
            alert('加载文章失败');
        }
    } else if (window.location.hash === '#about') {
        goToAboutPage();
    } else {
        currentView.value = 'list';
    }
}

async function loadAndRenderArticle(path) {
    try {
        const res = await fetch(path);
        if (!res.ok) {
            await tryLoadFallbackArticle(path); // 尝试 fallback
            return;
        }
        console.log("res:", res);
        const md = await res.text();
        console.log("md:", md);
        articleContent.value = marked.parse(md);
        currentView.value = 'article';
        window.location.hash = `article/${encodeURIComponent(path)}`;
        const found = articles.value.find(a => a.path === path);
        console.log("found:", found);
        if (found) currentArticle.value = found;
    } catch (e) {
        alert('加载文章失败');
    }
}

async function tryLoadFallbackArticle(originalPath) {
    const langMap = {'zh': 'en', 'en': 'zh'};
    const currentLang = lang.value;
    const fallbackLang = langMap[currentLang];
    const fallbackPath = originalPath.replace(`/data/${currentLang}/`, `/data/${fallbackLang}/`);

    try {
        const res = await fetch(fallbackPath);
        if (!res.ok) throw new Error('找不到 fallback 版本');
        const md = await res.text();
        articleContent.value = marked.parse(md);
        currentView.value = 'article';
        window.location.hash = `article/${encodeURIComponent(fallbackPath)}`;
        alert(`当前语言无此文章，已加载${fallbackLang === 'zh' ? '中文' : '英文'}版本`);
    } catch (e) {
        alert('文章不存在');
        goBackToList();
    }
}

async function loadConfigAndArticles() {
    try {
        const langVal = lang.value;
        const configRes = await fetch('./config-site.json');
        const data = await configRes.json();

        config.value = langVal === 'zh' ? { ...config, ...data.zh } : { ...config, ...data.en };

        document.title = config.title;
        const subtitleEl = document.querySelector('header p');
        if (subtitleEl) subtitleEl.textContent = config.subtitle;

        await loadArticles();
        window.addEventListener('hashchange', handleHashChange);
        handleHashChange();
    } catch (e) {
        alert('加载配置失败');
    }
}

async function loadArticles() {
    const langVal = lang.value;
    const res = await fetch(`data/${langVal}/article.json`);
    const data = await res.json();

    articles.value = data
        .filter(a => !['关于.md', 'About.md'].includes(a.path))
        .sort((a, b) => new Date(b.lastModified) - new Date(a.lastModified));
    console.log("articles:", articles.value);
    const allCategories = [...new Set(data.map(a => a.category))];
    categories.value = langVal === 'zh' ? ['首页', ...allCategories] : ['Home', ...allCategories];
}

async function goToAboutPage() {
    const langVal = lang.value;
    const filePath = langVal === 'zh' ? 'article/zh/关于.md' : 'article/en/About.md';
    try {
        const res = await fetch(filePath);
        if (!res.ok) throw new Error('加载失败');
        const md = await res.text();
        aboutContent.value = marked.parse(md);
        currentView.value = 'about';
        window.location.hash = 'about';
    } catch (e) {
        alert('加载关于页失败');
    }
}

function switchLang(newLang) {
    localStorage.setItem('lang', newLang);
    lang.value = newLang;
    console.log('切换语言为：', newLang);
    console.log("currentView:", currentView.value);
    console.log("currentArticle:", currentArticle.value);
    if (currentView.value === 'article' && currentArticle.value.path) {
        const langMap = {'zh': 'en', 'en': 'zh'};
        const targetLang = newLang;
        const fallbackLang = langMap[targetLang];
        const langRegex = /(.*\/)(zh|en)(\/.*)/;
        const targetPath = currentArticle.value.path.replace(langRegex, `$1${targetLang}$3`);

        loadAndRenderArticle(targetPath).catch(() => {
            // 如果目标语言不存在，显示 fallback
            loadAndRenderArticle(currentArticle.value.path); // 可能失败，需确保 fallback
            alert(`当前语言无此文章，已显示${fallbackLang === 'zh' ? '中文' : '英文'}版本`);
        });
    } else {
        loadConfigAndArticles();
    }
}

function filterByCategory(category) {
    if (lang.value === 'zh') {
        activeCategoryZh.value = category;
    } else {
        activeCategoryEn.value = category;
    }
    currentPage.value = 1;
}

const app = {
    setup() {
        onMounted(async () => {
            const savedTheme = localStorage.getItem('selectedTheme') || 'default';
            const themeLink = document.getElementById('theme-css');
            if (themeLink) {
                themeLink.href = `style/${savedTheme}.css`;
            }
            await loadConfigAndArticles();
        });

        return {
            lang,
            config,
            categories,
            currentView,
            filteredArticles,
            totalPages,
            paginatedArticles,
            currentPage,
            articleContent,
            currentArticle,
            aboutContent,
            formatDate,
            setPage,
            switchLang,
            changeTheme,
            goBackToList,
            loadAndRenderArticle,
            goToAboutPage,
            filterByCategory
        };
    }
};

const vueApp = createApp(app);
vueApp.mount('#app');
</script>
</body>
</html>